<template>
  <div>
    <el-form class="input-form"
      label-position="right"
      label-width="120px"
      ref="editForm"
      :rules="propRules"
      :disabled="propReadonly"
      :model="form"
    >
    <div class="form-unit">入库明细基本信息</div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="品名" prop="matrName">
            <matr-select
              v-model="form.matrId"
              :propText="propCurrentRow.matrName"
              :propColumns="selectMatrColumns"
              :propSupplierId="propInitData.supplierId"
              :propOmoc="propInitData.flagOmoc"
              :propConsignment="propInitData.flagConsignment"
              :propDisabled="propReadonly"
              propStyle="width:60vw"
              ref="matrGrid"
              @select="handleMatrSelect"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="物料品规" prop="matrSpec">
            <el-input v-model="form.matrSpec" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单品价格" prop="skuPrice">
            <el-input v-model="form.skuPrice" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="包装单位" prop="packageUnit">
            <matr-unit-select
              ref="matrUnitGrid"
              v-model="form.packageUnit"
              propUrl="/base/matrUnit/list"
              :propText="propCurrentRow.packageUnit"
              @select="handlePackageUnitChange"
              :propMatrId="form.matrId"
              :propPurchase="true"
              propValueField="unit"
              :propDisabled="strings.isBlank(form.matrId)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="包装数量" prop="packageQty">
            <el-input-number ref="qty" v-model="form.packageQty" :min="0" :max="999" label="包装数量"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="对应单品数量" prop="skuQty">
            <el-input v-model="form.skuQty" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="金额" prop="amount">
            <el-input v-model="form.amount" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库位名称" prop="locationName">
            <el-select v-model="form.locationId" filterable placeholder="请选择库位">
              <el-option v-for="item in locationList"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item >
            <el-button @click="setDefaultLocation">设为默认库位</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="批次" prop="lot">
            <el-input v-model="form.lot" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="效期" prop="expDate">
            <el-date-picker v-model="form.expDate" type="date" :format="dates.defaultDatePattern"  :picker-options="dates.pickerOptions.futureDate" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生产日期" prop="mfgDate">
            <el-date-picker v-model="form.mfgDate" type="date" :format="dates.defaultDatePattern"  :picker-options="dates.pickerOptions.date" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="注册证号" prop="certificateNo">
            <el-input v-model="form.certificateNo" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="灭菌日期" prop="sterilizationDate">
            <el-date-picker v-model="form.sterilizationDate" type="date" :format="dates.defaultDatePattern"  :picker-options="dates.pickerOptions.date" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发票号" prop="invoiceNo">
            <el-input v-model="form.invoiceNo" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="SN" prop="sn">
            <el-input v-model="form.sn" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="RFID" prop="rfid">
            <el-input v-model="form.rfid" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="UDI" prop="udi">
            <el-input v-model="form.udi" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" :autosize="{ minRows: 2, maxRows: 4}"/>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="form-unit" v-show="showSNList">SN明细</div>
      <el-row v-show="showSNList">
        <div style="height:500px;">
          <data-view
            v-show="form.id != null"
            propViewKey="wm_order_barcode"
            :propInitData="form"
            ref="childDataView"
            :propHidePageSearch="true"
            :propHideQueryButton="true"
          />
        </div>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import MatrSelect from '@/components/base/MatrSelect'
import MatrUnitSelect from '@/components/base/MatrUnitSelect'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      packageUnits: [],
      showSNList: true,
      locationList: [],
      selectMatrColumns: [
        { label: '品名', name: 'name', width: 200, search: true },
        { label: '品规',  name: 'spec', width: 150, search: true },
        { label: '厂商名称',  name: 'mfgName', search: true },
        { label: '单品单位',  name: 'skuUnit', width: 80, search: false },
        { label: '单品单价',  name: 'skuPrice', width: 80, search: false }
      ]
    }
  },
  created() {
    this.$emit('event-register', {
      validate: (callback) => {
        this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        let locationName = this.locationList.filter(location => location.id == this.form.locationId).map(location => location.name)[0]
        this.$set(this.form, 'locationName', locationName)
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        let queryWrapper = this.$newWrapper()
        if (formData.id) {
          queryWrapper.eq('workOrderItemId', formData.id)
        } else {
          queryWrapper.ne(1, 1)
        }
        this.$refs.childDataView.setQueryWrapper(queryWrapper)
        this.$set(this.form, 'warehouseId', initData.warehouseId)
        if (this.propStatus == 'addnew') {
          this.$set(this.form, 'workOrderId', initData.id)
        } else {
          this.$set(this.form, 'packageRate', this.form.skuQty / this.form.packageQty)
        }
      },
      afterSave: () => {
        this.propParentPage.$emit('refresh-row')
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
        this.$refs.childDataView.fetchData()
      },
      beforeClose: () => {
        return true
      }
    })
    this.getLocationList(this.propInitData.warehouseId)
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propParentPage: Object
  },
  components: {
    MatrSelect,
    MatrUnitSelect
  },
  computed: {
  },
  watch: {
    //当包的换算比率发生变化时，重新计算单品数量和总价
    'form.packageRate': {
      handler(newVal) {
        this.form.skuQty = this.form.packageQty * newVal
        this.form.amount = this.form.skuPrice * this.form.skuQty
      },
      deep: true
    },
    //包装数量发生变化时，重新计算单品数量和总价
    'form.packageQty': {
      handler(newVal) {
        this.form.skuQty = this.form.packageRate * newVal
        this.form.amount = this.form.skuPrice * this.form.skuQty
      },
      deep: true
    },
    'form.skuQty': {
      handler(newVal) {
        if (isNaN(newVal)) {
          this.form.skuQty = ''
        }
      },
      deep: true
    },
    'form.amount': {
      handler(newVal) {
        if (isNaN(newVal)) {
          this.form.amount = ''
        }
      },
      deep: true
    }
  },
  methods: {
    // 从手工入库过来，在入库单选择的第一条耗材为默认耗材数据
    // setDefaultMatr(id) {
    //   let item = this.matrs.find(matr => matr.id == id)
    //   if (item) {
    //     this.handleMatrSelect(item)
    //   }
    // },
    fetchMatr() {
      let that = this
      if (!this.propParent.viewFormVisible) {
        return
      }

      let {supplierId, flagConsignment, flagOmoc} = this.propInitData
      if (this.strings.isBlank(supplierId)) {
        return
      }

      let wrapper = this.$newWrapper()
        .eq('supplierId', supplierId)
        .eq('flagConsignment', flagConsignment)
        .eq('flagOmoc', flagOmoc)
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions)
      }
      // this.$ajax.get('/base/matr/list', {params}).then(resp => {
      //   that.matrs = resp.data
      //   if (!that.form.id && that.propInitData.refId > 0) {
      //     that.setDefaultMatr(that.propInitData.refId)
      //   }
      // })
    },
    //选择耗材事件
    handleMatrSelect(item) {
      let {id, name, spec, flagConsignment, flagOmoc, skuPrice, skuUnit, mfgName, certificateNo} = item

      if (flagConsignment !== this.propInitData.flagConsignment) {
        this.utilMessage.error(`必须是${this.propInitData.flagConsignment ? '' : '非'}寄售入库耗材才能入库`)
        return
      }
      if (flagOmoc !== this.propInitData.flagOmoc) {
        this.utilMessage.error(`必须是${this.propInitData.flagOmoc ? '' : '非'}一物一码耗材才能入库`)
        return
      }

      if (skuPrice == null || skuPrice == 0) {
        this.utilMessage.error(`${name}没有价格，请先至基础数据-耗材管理中维护价格`)
        return
      }
      this.$set(this.form, 'matrId', id)
      this.$set(this.form, 'matrName', name)
      this.$set(this.form, 'matrSpec', spec)
      this.$set(this.form, 'skuPrice', skuPrice)
      this.$set(this.form, 'skuUnit', skuUnit)
      this.$set(this.form, 'certificateNo', certificateNo)
      this.$set(this.form, 'mfgName', mfgName)
      this.$refs.matrUnitGrid.handleFocus()
      this.getDefaultLocation(id, this.form.warehouseId, this.form.packageUnit)
    },
    //根据耗材获取默认库位
    getDefaultLocation(matrId, warehouseId, packageUnit) {
      this.$ajax.get('/location/limit_matr/getDefaultLocation', {params: {matrId, warehouseId, 'packageUnit': packageUnit}}).then(resp => {
        this.$set(this.form, 'locationId', resp.data.id)
        this.$set(this.form, 'locationName', resp.data.name)
      })
    },
    getLocationList(warehouseId) {
      let wrapper = this.$newWrapper()
        .eq('warehouseId', warehouseId)
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions)
      }
      this.$ajax.get('/base/location/list', {params}).then(resp => {
        this.locationList = resp.data
      })
    },
    //耗材单位变更时，重新计算换算比
    handlePackageUnitChange(item) {
      item && this.$set(this.form, 'packageRate', item.rate)
      this.$refs.qty.$el.querySelector('input').focus()
    },
    setDefaultLocation() {
      this.$ajax.post('/location/limit_matr/save', this.form).then(resp => {
        if (resp.success) {
          this.utilMessage.success('设置成功')
        } else {
          this.utilMessage.error(resp.msg)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .container {
    width: 100%;
    height: 100%;
  }
</style>
